import os.path

from Images import MuImages
from tools import MuTool


class MuPdf:
    def __init__(self):
        self.tools = MuTool()
        self.message = None
        self.env = self.tools.get_os()
        self.image = MuImages()
    # 获取错误信息
    def get_error_message(self):
        return self.message
    # mac pdf拆分
    def __mac_split(self, input_file_path:str, output_file_path:str|None=None, img_type:str|None=None):
        return self.__windows_split(input_file_path, output_file_path, img_type)
    # linux pdf拆分
    def __linux_split(self, input_file_path:str, output_file_path:str|None=None, img_type:str|None=None):
        return self.__windows_split(input_file_path, output_file_path, img_type)
    # windows pdf拆分
    def __windows_split(self, input_file_path:str, output_file_path:str|None=None,img_type:str|None=None):
        import fitz
        import os
        try:
            if not img_type:
                img_type = "png"
            doc = fitz.open(input_file_path)
            total = doc.page_count
            zoom = 200
            for pg in range(total):
                page = doc[pg]
                zoom = int(zoom)  # 值越大，分辨率越高，文件越清晰
                rotate = int(0)

                trans = fitz.Matrix(zoom / 100.0, zoom / 100.0).prerotate(rotate)
                pm = page.get_pixmap(matrix=trans, alpha=False)
                if not os.path.exists(output_file_path):
                    os.makedirs(output_file_path, exist_ok=True)
                pgs = str(pg+1)
                save = os.path.join(output_file_path, f'{pgs}.{img_type}' )
                pm.save(save)
            doc.close()
        except Exception as e:
            self.message = str(e)
            return False
        return True

    # pdf拆分
    def split_pdf(self, input_file_path:str, output_file_path:str|None=None, img_type:str|None=None):
        '''

        :param input_file_path: 输入文件
        :param output_file_path: 输出文件夹
        :param img_type: 图片类型
        :return:
        '''
        if self.tools.is_empty(input_file_path):
            self.message = "输入文件为空"
            return False
        if not os.path.exists(input_file_path):
            self.message = "文件不存在"
            return False
        env = self.tools.get_os()
        if env == "win":
            return self.__windows_split(input_file_path, output_file_path, img_type)
        elif env == "linux":
            return self.__linux_split(input_file_path, output_file_path, img_type)
        elif env == "mac":
            return self.__mac_split(input_file_path, output_file_path,img_type)
        elif env == "other":
            self.message = "暂时不支持的系统"
            return False
        return True
    # pdf合并
    def jion_pdf(self,input_file_path:str|list, output_file_path:str|None=None):
        '''
        :param input_file_path: 输入pdf
        :param output_file_path: 输出pdf
        :return:
        '''
        import PyPDF2
        if self.tools.is_empty(input_file_path):
            self.message = "输入文件为空"
            return False
        try:
            if isinstance(input_file_path,str):
                input_file_path = input_file_path.split(",")
            merger = PyPDF2.PdfMerger()
            for file_path in input_file_path:
                # 添加第一个PDF文件
                merger.append(open(file_path, 'rb'))

            # 添加第二个PDF文件
            # merger.append(open('file2.pdf', 'rb'))

            # 写入合并后的PDF文件
            with open(output_file_path, 'wb') as f:
                merger.write(f)

            # 关闭合并器
            merger.close()
        except Exception as e:
            self.message = str(e)
            return False
        return True
    def __linux_pptx_to_pdf(self, input_file_path:str, output_file_path:str):
        return self.__win_pptx_to_pdf(input_file_path, output_file_path)
    def __win_pptx_to_pdf(self, input_file_path:str, output_file_path:str):
        import comtypes.client
        try:
            powerpoint = comtypes.client.CreateObject('PowerPoint.Application')
            # powerpoint.Visible = True  # 设置为False以在后台运行

            # 打开PPTX文件
            presentation = powerpoint.Presentations.Open(input_file_path)

            # 另存为PDF
            presentation.SaveAs(output_file_path, 32)  # 使用整数32表示PDF格式

            # 关闭PPTX文件（不保存更改）
            presentation.Close()
        except Exception as e:
            self.message = str(e)
            return False
        return True
    def __pptx_to_pdf(self, input_file_path:str, output_file_path:str):
        if self.env =='win':
            return self.__win_pptx_to_pdf(input_file_path, output_file_path)
        elif self.env =='linux':
            return self.__linux_pptx_to_pdf(input_file_path, output_file_path)
        elif self.env =='mac':
            self.message = "暂时不支持的转换"
            return False
        return True
    def __doc_to_pdf(self, input_file_path:str, output_file_path:str):
        from docx2pdf import convert
        try:
            convert(input_file_path, output_file_path)
        except Exception as e:
            self.message = str(e)
            return False
        return True
    def __excel_to_pdf(self, input_file_path:str, output_file_path:str):
        import subprocess
        # print(output_file_path.rsplit('/', 1)[0])
        command = [
            'libreoffice', '--headless', '--convert-to', 'pdf',
            '--outdir', output_file_path.rsplit('/', 1)[0],  # 输出目录
            input_file_path
        ]
        result = subprocess.run(command, capture_output=True, text=True)

        # 检查命令是否成功执行
        if result.returncode != 0:
            print(f"Error converting '' to PDF:\n{result.stderr}")
        else:
            print(f"Successfully converted '' to {output_file_path}")
    def __pdf_to_pptx(self, input_file_path:str, output_file_path:str):
        import fitz
        try:
            max_slides = 999
            # 打开PDF文件
            pdf_document = fitz.open(input_file_path)

            # 创建一个新的PPTX文件
            # prs = Presentation()
            allIms = []
            timestr = self.tools.get_md5()
            if not os.path.exists(timestr):
                os.makedirs(timestr, exist_ok=True)
            # 遍历PDF的每一页，直到达到max_slides
            for page_num in range(min(max_slides, len(pdf_document))):
                page = pdf_document.load_page(page_num)
                pix = page.get_pixmap()

                # 保存页面为临时图像文件
                temp_image_path = f"{timestr}/temp_page_{page_num}.png"
                pix.save(temp_image_path)
                allIms.append(temp_image_path)
            self.image.splicing_images(allIms,output_file_path,'pptx')
            if os.path.exists(timestr):
                self.tools.delete_path(timestr)
        except Exception as e:
            self.message = str(e)
            return False
        return True

    def __pdf_to_docx(self, input_file_path:str, output_file_path:str):
        from pdf2docx import Converter
        try:
            cv = Converter(input_file_path)

            # 转换第一页
            cv.convert(output_file_path, start=0)

            # 关闭转换器
            cv.close()
        except Exception as e:
            self.message = str(e)
            return False
        return True
    def __pdf_to_xlsx(self, input_file_path:str, output_file_path:str):
        strs = self.tools.get_md5()
        new_file_path = "./"+strs
        if not os.path.exists(new_file_path):
            os.mkdir(new_file_path)
        self.split_pdf(input_file_path,new_file_path,"png")
        img_files = self.tools.get_path_file(new_file_path)
        # print(img_files)
        # return True
        bol = self.image.splicing_images(img_files,output_file_path,"xlsx",0,0,None)
        if os.path.exists(new_file_path):
            self.tools.delete_path(new_file_path)
        self.message = self.image.get_error_message()
        return bol
    def pdf_to_other(self, input_file_path:str, output_file_path:str,file_type:str|None=None):
        if not file_type and not output_file_path:
            self.message = "文件类型为空"
            return False
        if not file_type:
            file_type = self.tools.get_file_suffix(output_file_path)
        if file_type=="docx" or file_type=="doc" or file_type=="word":
            return self.__pdf_to_docx(input_file_path, output_file_path)
        elif file_type=="ppt" or file_type=="pptx":
            return self.__pdf_to_pptx(input_file_path, output_file_path)
        elif file_type=="xlsx" or file_type=="excel" or file_type=="xls":
            return self.__pdf_to_xlsx(input_file_path, output_file_path)
        pass
    # 其他类型转pdf
    def otherType2Pdf(self, input_file_path:str|list, output_file_path:str,file_type:str|None=None):
        if self.tools.is_empty(input_file_path):
            self.message = "输入文件为空"
            return False
        if not os.path.exists(input_file_path):
            self.message = "文件不存在"
            return False
        if not file_type:
            file_type = self.tools.get_file_suffix(input_file_path)
        # print(file_type)
        if file_type == "ppt" or file_type == "pptx":
            return self.__pptx_to_pdf(input_file_path, output_file_path)
        elif file_type == "doc" or file_type == "docx" or file_type == "word":
            return self.__doc_to_pdf(input_file_path, output_file_path)
        elif file_type == "xls" or file_type == "xlsx" or file_type == "excel":
            self.message = "暂时不支持的转换"
            return False
            # print('haha')
            # return self.__excel_to_pdf(input_file_path, output_file_path)
        self.message = "暂时不支持的转换"
        return False
    def convert_type(self, input_file_path:str|list, output_file_path:str|None=None,file_type:str|None=None):
        if self.tools.is_empty(input_file_path):
            self.message = "输入文件为空"
            return False
        if not os.path.exists(input_file_path):
            self.message = "文件不存在"
            return False
        if not file_type and not output_file_path:
            self.message = "文件类型为空"
            return False
        if not file_type:
            output_file_path_array = output_file_path.split(".")
            if not output_file_path_array[-1] or output_file_path_array[-1] not in ["pdf","docx",'word',"excel",'doc','docx',"pptx",'ppt'] :
                self.message = "文件类型为空"
                return False
            file_type = output_file_path_array[-1]
        print(file_type)
